package com.sun.umbrella.controller.login;

import com.sun.core.enums.BaseErrorEnum;
import com.sun.core.web.result.Result;
import com.sun.umbrella.remote.RemoteService;
import com.sun.umbrella.service.bns.user.UserEtcService;
import com.sun.umbrella.service.shiro.enums.UmbrellaEnum;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

import static org.apache.shiro.web.filter.authc.FormAuthenticationFilter.DEFAULT_ERROR_KEY_ATTRIBUTE_NAME;


/**
 * @author Jay
 * @version v1.0
 * @description 登录、退出接口
 * @date 2017-11-19 17:06
 */
@Slf4j
@Controller
public class LoginController {


    @Autowired
    private RemoteService remoteService;

    @Autowired
    private UserEtcService userEtcService;

///    /**
//     * 登录接口
//     *
//     * @param request
//     * @return
//     */
//    @RequestMapping(value = "/login")
//    @ResponseBody
//    public Result<?> login(HttpServletRequest request) {
//        String exceptionClassName = (String) request.getAttribute(DEFAULT_ERROR_KEY_ATTRIBUTE_NAME);
//        // 如果返回错误信息 则说明登录失败了
//        if (!StringUtils.isEmpty(exceptionClassName)) {
//            log.info("登录失败，错误信息为:{}", exceptionClassName);
//            if (UnknownAccountException.class.getName().equals(exceptionClassName)) {
//                return Result.wrapErrorResult(UmbrellaEnum.LOGIN_ERROR.getCode(), "用户名不存在");
//            }
//            if (IncorrectCredentialsException.class.getName().equals(exceptionClassName)) {
//                return Result.wrapErrorResult(UmbrellaEnum.LOGIN_ERROR.getCode(), "用户名或密码错误");
//            }
//            if (AuthenticationException.class.getName().equals(exceptionClassName)) {
//                return Result.wrapErrorResult(UmbrellaEnum.LOGIN_ERROR.getCode(), "登录认证失败");
//            }
//            if (ExcessiveAttemptsException.class.getName().equals(exceptionClassName)) {
//                return Result.wrapErrorResult(UmbrellaEnum.LOGIN_ERROR.getCode(), "今日失败重试次数已达上限");
//            }
//            return Result.wrapErrorResult(BaseErrorEnum.SYS_ERROR.getCode(), "登录认证出现了未知错误");
//        }
//        Subject subject = SecurityUtils.getSubject();
//        String userName = subject.getPrincipal().toString();
//        //查询登录用户的信息返回
//        return Result.wrapSuccessfulResult(userEtcService.queryUserInfoWhenLoginSuccess(userName));
//    }


    /**
     * 登录接口
     *
     * @param userName
     * @param password
     * @return
     */
    @RequestMapping(value = "/login")
    @ResponseBody
    public Result<?> login(String userName, String password) {
        String error = null;
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(userName, password);
        token.setRememberMe(true);
        try {
            subject.login(token);
        } catch (UnknownAccountException e) {
            error = "用户名或密码错误";
        } catch (IncorrectCredentialsException e) {
            error = "用户名或密码错误";
        } catch (AuthenticationException e) {
            //其他错误，比如锁定，如果想单独处理请单独catch处理
            error = "其他错误：" + e.getMessage();
        }
        if(error != null) {
            return Result.wrapErrorResult(-1, error);
        }
        //查询登录用户的信息返回
        return Result.wrapSuccessfulResult(userEtcService.queryUserInfoWhenLoginSuccess(userName));
    }

    /**
     * 退出登录
     *
     * @return
     */
    @RequestMapping("/logout")
    @ResponseBody
    public Result loginOut() {
        try {
            Object principal = SecurityUtils.getSubject().getPrincipal();
            if (principal == null) {
                return Result.wrapSuccessfulResult("logout success");
            }
            if (remoteService.logout(principal.toString())) {
                return Result.wrapSuccessfulResult("logout success");
            }
            return Result.wrapErrorResult(BaseErrorEnum.UNKNOWN_ERROR);
        } catch (Exception e) {
            log.error("退出登录异常,异常信息为:{}", e);
            return Result.wrapErrorResult(BaseErrorEnum.UNKNOWN_ERROR);
        }
    }


///    public static void main(String[] arsg) {
//        System.out.println(new SimpleHash("MD5", "123456", ByteSource.Util.bytes("y234567"), 1024));
//    }
}
